package dse.messages.multiversion;

import dse.*;
import dse.messages.*;

public class RequestVersionMessageHandler extends MessageSender implements MessageHandler {
	private DataObject dobj;
	private VersionReader versionReader;
	
	public RequestVersionMessageHandler (
			Experiment experiment, 
			DataObject dobj, 
			VersionReader versionReader
			)
	{
		super(experiment);
		
		this.dobj = dobj;
		this.versionReader = versionReader;
	}
	
	
	@Override
	public boolean acceptMessage(Message message) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void messageInterupted(ExperimentRecorder recorder, Message message,
			double time) {
		// TODO Auto-generated method stub
		recorder.debug(this, "msgIntrpt: " + message, time);
		versionReader.readVersion(recorder, null, time, message.to());
	}

	@Override
	public void messageReceived(ExperimentRecorder recorder, Message message, double time) {
		// TODO Auto-generated method stub
		recorder.debug(this, "msgRcvd: " + message, time);
		if (message.messageType() != MessageType.RequestVersion) {
			recorder.warn(
					"RequestVersionMessageHandler recieved " + 
					message.messageType() + " message."
					);
			return;
		}			
		// What do we know about the share?
		Node receiver = message.to();
		
		// Does the receiver have the share?
		DataShare share = receiver.getDataShare(dobj);
		if (share != null)
		{
			// Then we need to send a new message BACK (thats why to and from
			// are reversed!
			Message m = super.createVersionResponseMessage(
					receiver, message.from(), share.getVersions(), 
					message.purpose(), versionReader);
			recorder.debug(this, "new msg: " + m, time);
			experiment.messageQueue().enqueueMessage(m, time);
		}
		else
		{
			this.messageInterupted(recorder, message, time);
		}
	}
}
